/**
 * 
 * 
 *  
 *====================================================
 * 文件名称: EncodingFilter.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    Mar 3, 2009		(创建:创建文件)
 * 2.    Mar 3, 2009        根据 注释 规范进行调整
 *====================================================
 * 类描述： 编码过滤器
 * 
 */
package com.devframe.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * <pre>
 * 编码过滤器
 * </pre>
 * 
 * <br>
 * JDK版本:1.3
 * 
 * @author 姚建斌、陈雄华
 * @version 1.0
 * @since 1.0
 */
public class EncodingFilter implements Filter {
	/**
	 * 声明encoding
	 */
	protected String encoding = "utf-8";

	/**
	 * filterConfig
	 */
	protected FilterConfig filterConfig = null;

	/**
	 * 是否将客户端报告的Encoding设置忽略，强制使用我们设置的Encoding? 默认是忽略
	 */
	protected boolean ignore = true;

	/**
	 * destroy
	 */
	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

	/**
	 * 对当前request进行encoding设置（如果不选择忽略客户端设置的话）
	 * 
	 * @param request
	 *            当前处理的SevletRequest
	 * @param response
	 *            当前处理的SevletResponse
	 * @param chain
	 *            当前Filter链
	 * @exception IOException
	 *                I/O错误发生
	 * @exception ServletException
	 *                Servelt错误发生
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		// 若设置覆盖客户端设置或者客户端设置为null，则应用
		// 当前的encoding设置(从初始化参数中读取)
		if (ignore || (request.getCharacterEncoding() == null)) {
			String encoding = selectEncoding(request);

			if (encoding != null) {
				request.setCharacterEncoding(encoding);
			}
		}

		chain.doFilter(request, response);
	}

	/**
	 * 初始化
	 * 
	 * @param filterConfig
	 *            Filter设置对象
	 * @throws ServletException
	 *             ServletException
	 */
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		if (value == null) {
			this.ignore = true;
		} else if (value.equalsIgnoreCase("true")) {
			this.ignore = true;
		} else if (value.equalsIgnoreCase("yes")) {
			this.ignore = true;
		} else {
			this.ignore = false;
		}

	}

	/**
	 * <b>功能说明：返回当前的Encoding设置</b><br>
	 * 
	 * @param request
	 *            request
	 * @return String 
	 */

	protected String selectEncoding(ServletRequest request) {
		String encoding=this.encoding;
		//return (this.encoding);
		return encoding;
	}

}
